import http from '@/api/index';
import { getUUID, isEmpty } from '@/assets/js/utils';

enum API {
    GET_APP_VERSION = '/translate/appVersion/getLastAppVersion', //获取APP版本信息
    GET_SYSTEM_CONFIG = '/translate/sysConfig/getSysConfig', //获取系统配置
    ADD_USER_SYSTEM_INFO = '/translate/userInfoExt/addUserInfoExt', //新增用户ip地址等系统信息
    GET_QINIU_TOKEN = '/property/qiniu/getToken', //获取七牛上传token
    ADD_FEEDBACK = '/translate/feedback/add' //新增意见反馈
}

//获取APP版本信息
export function getAppVersion(data: any) {
    return http.post({
        url: API.GET_APP_VERSION,
        data,
        errToast: false
    });
}

//获取系统配置
export function getSystemConfig(data: any) {
    return http.post({
        url: API.GET_SYSTEM_CONFIG,
        data,
        errToast: false
    });
}

//新增用户ip地址等系统信息
export function addUserSystemInfo(data: any) {
    return http.post({
        url: API.ADD_USER_SYSTEM_INFO,
        data,
        errToast: false
    });
}


//获取七牛上传token
export function getQiniuToken() {
    return http.post({
        url: API.GET_QINIU_TOKEN
    });
}

//七牛上传文件
// file:文件对象；onProgress：上传进度回调函数
export function updateFile(file: any, onProgress?: Function): any {
    return new Promise(async (resolve, reject) => {
        let token = null;
        let [result, err] = await getQiniuToken();
        if (result) {
            token = result;
        }
        if (isEmpty(token)) {
            resolve([null, '上传token失效']);
            return;
        }
        if (!file) {
            resolve([null, '上传文件不能给空']);
            return;
        }
        // let base64File: any = await blobToBase64(file);
        let keyname = getUUID();
        let uploadTask = uni.uploadFile({
            url: import.meta.env.VITE_APP_UPLOAD_URL,
            filePath: file,
            name: 'file',
            method: 'POST',
            formData: {
                key: keyname,
                token: token
            },
            success: (res: any) => {
                if (res.statusCode == '200') {
                    let { key } = JSON.parse(res.data);
                    resolve([`${import.meta.env.VITE_APP_CDN_URL}/${key}`, null]);
                } else {
                    let { error } = JSON.parse(res.data);
                    resolve([null, error]);
                }
            },
            fail: err => {
                resolve([null, err]);
            }
        });
        uploadTask.onProgressUpdate(({ progress }) => {
            if (onProgress) onProgress(progress);
        });
    });
}

//新增意见反馈
export function addFeedback(data: any) {
    return http.post({
        url: API.ADD_FEEDBACK,
        data
    });
}
